package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ChatHistoryMapper;
import com.ruoyi.system.domain.ChatHistory;
import com.ruoyi.system.service.IChatHistoryService;
import com.ruoyi.system.domain.ChatHistoryDTO;

import java.util.UUID;
import java.util.stream.Collectors;
/**
 * 试用申请管理Service业务层处理
 *
 * @author hak
 * @date 2024-11-13
 */
@Service
public class ChatHistoryServiceImpl implements IChatHistoryService
{
    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    /**
     * 查询用户下面的
     *
     * @param userId 用户ID
     * @return 用户ID的所有历史对话
     */
    @Override
    public List<ChatHistoryDTO> selectChatHistoryByUserId(String userId)
    {
        List<ChatHistory> chatHistories = chatHistoryMapper.selectChatHistoryByUserId(userId);

        // 转换为DTO对象，只保留需要的三个字段
        return chatHistories.stream()
                .map(history -> {
                    ChatHistoryDTO dto = new ChatHistoryDTO();
                    dto.setChatId(history.getChatId());
                    dto.setLastMessageTime(history.getLastMessageTime());
                    dto.setTitle(history.getTitle());
                    return dto;
                })
                .collect(Collectors.toList());
    }
    @Override
    public String addChatHistory(String userId, String title) {
        ChatHistory chatHistory = new ChatHistory();
        // 生成UUID作为chatId
        String chatId = UUID.randomUUID().toString();
        chatHistory.setChatId(chatId);
        chatHistory.setUserId(userId);
        chatHistory.setTitle(title);
        chatHistory.setLastMessageTime(DateUtils.getNowDate());
        chatHistory.setStatus(0); // 假设0表示正常状态

        chatHistoryMapper.insertChatHistory(chatHistory);
        return chatId;
    }

    @Override
    public int deleteChatHistory(String chatId) {
        if (StringUtils.isEmpty(chatId)) {
            throw new ServiceException("对话ID不能为空");
        }
        return chatHistoryMapper.deleteChatHistory(chatId);
    }
}
